import React, { useState, useEffect } from "react";
import { List, Row, Col, Modal, message, Button, Tooltip,Select } from "antd";
import axios from "axios";
import { formatStamp,timesago,arrFindToObj,urlImgToBlob,blobToBase64 } from "../filters/index"
import servicePath from "../config/apiUrl";
import PaginationTmp from '../components/Pagination'
import "../static/css/ArticleList.css";
import SearchTmp from "../components/SearchTmp"
const { confirm } = Modal;
const { Option,OptGroup  } = Select;
function TopicList(props) { 
  const [list, setList] = useState([])
  const [shareTopicType, setShareTopicType] = useState([]) 
  const [loading, setLoading] = useState(false) 
  const [paginationTotal, setPaginationTotal] = useState() 
  const [pageCurrent, setPageCurrent] = useState(1) 
  const [searchType,setSearchType] = useState()
  const [typeInfo, setTypeInfo] = useState([]); // 文章类别信息
  //得到文章列表
  const getList = (pageSize,pageIndex,searchType,searchTxt,startTime,endTime) => {
    searchType = searchType?searchType:"";
    
    let searchID
    if(shareTopicType.length && searchType){
      if(arrFindToObj("shareTopicTitle","id",searchType,shareTopicType) === `${searchType}检索失败`){
        searchID = ""
        setSearchType("")
        // message.warn(`${searchType} 精确检索失败`)
      }else{
        searchID = arrFindToObj("shareTopicTitle","id",searchType,shareTopicType)
      }
      
    } else{
      searchID = ""
    }
    if(!searchType){
      searchID = ""
    }
    console.log(shareTopicType,'0000',searchType);
    console.log('222222222',searchID);
    // arrFindToObj("id","shareTopicTitle",item.topic_id,shareTopicType)
    
    pageSize = pageSize?pageSize:10
    pageIndex = pageIndex?pageIndex:1
    searchTxt = searchTxt?searchTxt:""
    startTime = startTime?startTime:""
    endTime = endTime?endTime:""
    setLoading(true)
    axios({
      method: "get",
      url: servicePath.getTopicList,
      params: {
        pageSize,
        pageIndex,
        searchTxt,
        searchID,
        endTime,
        startTime
      },
      // dataType: 'json',
      withCredentials: false,
      header: { "Access-Control-Allow-Origin": "*" }
    }).then(res => {
      setPaginationTotal(res.data.data.total)
      setList(res.data.data.list);
      setLoading(false)
    }).catch((err)=>{
      message.error(err.response.data.data)
      if(err.response.status === 401){
        props.history.push("/login")
      }
      setLoading(false)
    })
  };
  const resetSearch = () =>{
    setSearchType('')
    getList(10,1,"")
    PaginationSizeChanger(1,10)
    setSearchType("")
  }
  const searchData = (searchTxt,searchTime) => {
    
    setPageCurrent(1)
    getList(10,1,searchType,searchTxt,searchTime?new Date(searchTime[0]).getTime():'',searchTime?new Date(searchTime[1]).getTime():'')
  }
  //修改文章
  const updateArticle = (id, checked) => {
    props.history.push("/index/addTopicItem/" + id);
  };
  //得到文章类别列表
  const getShareTopic = () => {
    setLoading(true)
    axios({
      method: "get",
      url: servicePath.getShareTopic,
      withCredentials: false,
      header: { "Access-Control-Allow-Origin": "*" }
    }).then(res => {
      console.log('5555555',res.headers);
      
      setShareTopicType(res.data.list)
      getList(10,1);
      let type = []
      res.data.list.map((res,index) => {
        type.push(
          {
            typeName: res.shareTopicTitle,
            id: res.id
          }
        )
      })
      setTypeInfo(type);
      setLoading(false)
      
    }).catch((err)=>{
      message.error(err.response.data.data)
      if(err.response.status === 401){
        props.history.push("/login")
      }
      setLoading(false)
    })
  };
  useEffect(() => {
    getShareTopic()
  }, []);
  //删除文章的方法
  const delArticle = id => {
    confirm({
      title: "确定要删除这篇博客文章吗?",
      content: "如果你点击OK按钮，文章将会永远被删除，无法恢复。",
      onOk() {
        axios(servicePath.delTopicList + id, { withCredentials: false }).then(
          res => {
            message.success("文章删除成功");
            getList(10,1);
          }
        ).catch((err)=>{
          message.error(err.response.data.data)
          if(err.response.status === 401){
            props.history.push("/login")
          }
          setLoading(false)
        })
      },
      onCancel() {
        message.success("没有任何改变");
      }
    });
  };

  const PaginationSizeChanger = (page, pageSize) => {
    console.log(page,'252525',pageSize);
    getList(pageSize,page)
    setPageCurrent(page)
  }
  // const slotTmp = <Input placeholder="类别检索" value={ searchType } style={{ width: "30%",marginRight:"15px" }} onChange={e => { setSearchType(e.target.value); }} /> 
  // value={ selectedType ? selectedType:undefined }
  let slotTmp = <Select
    size="middle"
    style={{marginRight:'15px',minWidth:'180px'}}
    placeholder="选择专题类"
    defaultValue=" "
    onChange={(val) => {
      setSearchType(val)
    }}
  >
    <OptGroup label="检索类别" style={{borderBottom:'1px solid #ccc'}}>
      <Option value=" ">全部</Option>
    </OptGroup>
    {typeInfo.map((item, index) => {
      return (
        <Option key={index} value={item.typeName}>
          {item.typeName}
        </Option>
      );
    })}
  </Select>  
  return (
    <div>
      <SearchTmp searchData={ searchData } resetSearch={ resetSearch } slotTmp = { slotTmp }  />
      {/* <img src={list[0].topicBcg.data} ></img> */}
      <List
        loading = {loading}
        header={
          <Row className="list-div">
            <Col span={4}>
              <b>标题</b>
            </Col>
            <Col span={3}>
              <b>类别</b>
            </Col>
            <Col span={4}>
              <b>简介</b>
            </Col>
            <Col span={3}>
              <b>浏览量</b>
            </Col>
            <Col span={3}>
              <b>发布时间</b>
            </Col>
            <Col span={3}>
              <b>更新时间</b>
            </Col>
            {/* <Col span={3}>
              <b>简介</b>
            </Col> */}

            <Col span={4}>
              <b>操作</b>
            </Col>
          </Row>
        }
        bordered
        dataSource={list}
        renderItem={item => (
          <List.Item>
            <Row className="list-div">
              <Col span={4}>{item.title}</Col>  
              <Col span={3}>{arrFindToObj("id","shareTopicTitle",item.topic_id,shareTopicType)}</Col>
              {/* <Col span={3}>{
                // item.topic_id
                arrFindToObj("id","title",item.topic_id,shareTopicType)
              }</Col> */}
              <Col span={4}>
                <Tooltip placement="left" title={`${item.introduce?item.introduce:'暂无'}`}>
                  {item.introduce?item.introduce:'-'}
                </Tooltip>
              </Col>
              <Col span={3}>{item.view_count}</Col>
              <Col span={3}>{formatStamp(item.addTime)}</Col>
              <Col span={3}>{timesago(item.updateTime)}</Col>
              {/* <Col span={3}>
                <span>{item.article_content}</span>
              </Col> */}

              <Col span={4}>
                <Button type="link" onClick={()=> {
                  updateArticle(item.id)
                }}>修改</Button>&nbsp;
                <Button
                  type="link"
                  danger
                  onClick={() => {
                    delArticle(item.id);
                  }}
                >
                  删除{" "}
                </Button>
              </Col>
            </Row>
          </List.Item>
        )}
      />
      {
        paginationTotal>10?<PaginationTmp total={ paginationTotal } current={ pageCurrent } PaginationSizeChanger={PaginationSizeChanger} />:""
      }
      {/* <img src={blobToBase64(list[0].topicBcg.data)} ></img> */}
      {/* {
        list[0]?
        <img src={blobToBase64(list[0].topicBcg.data)}></img>
        : ""
      }  */}
      
      {/* {
        console.log('===================================='),
        console.log(list[0]?list[0].topicBcg.data:"****")
      } */}
      
    </div>
  );
}

export default TopicList;
